<template>
  <div>
    <!-- 搜索栏 -->
    <div class="search-bar" style="display: flex; justify-content: center; margin-bottom: 20px;">
      <!-- 分类选择 -->
      <el-select v-model="selectedCategory" placeholder="选择分类" class="category-select"
        style="width: 20%; max-width: 150px; margin-right: 10px;">
        <el-option label="全部" value="全部"></el-option>
        <el-option label="音阶与调式" value="音阶与调式"></el-option>
        <el-option label="节奏与韵律" value="节奏与韵律"></el-option>
        <el-option label="传统记谱法" value="传统记谱法"></el-option>
        <el-option label="曲式与结构" value="曲式与结构"></el-option>
        <el-option label="其他" value="其他"></el-option>
      </el-select>
  
      <el-input 
      placeholder="搜索乐理知识" 
      v-model="queryStr" 
      class="input-with-select" 
      style="width: 50%; max-width: 400px; margin-right: 10px;">
      </el-input>
  
      <!-- 查询按钮 -->
      <el-button 
      class="button" 
      @click="queryInfo" 
      style="margin-top: 6px; background-color: transparent; border: 1px solid #dcdfe6; color: #333;">查询</el-button>
    </div>
  
    <!-- 内容展示 -->
    <el-row gutter="30">
      <el-col v-for="knowledge in filteredKnowledge" :key="knowledge.theory_knowledge_id" :span="6" class="knowledge-item">
        <el-card class="knowledge-out">
          <img :src="'http://localhost:8080/images/upload/' + knowledge.cover_image" alt="乐理知识封面"
            class="knowledge-cover" @click="goToNotationDetail(knowledge)"/>
          <div class="knowledge-info">
            <h4>{{ knowledge.name }}</h4>
            <p>{{ knowledge.type }}</p>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
  
  <el-pagination
  :current-page.sync="currentPage"
  :page-size="pageSize"
  :total="totalItems"
  layout="prev, pager, next"
  @current-change="handlePageChange"
/>

  </template>
<script>
import axios from 'axios';

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 12,
      totalItems: 20,

      selectedCategory: '全部', // 选择的分类
      knowledgeList: [], // 用户收藏的所有乐理知识数据
      filteredKnowledge: [], // 过滤后的乐理知识列表
      queryStr: '', // 查询条件
      userId: sessionStorage.getItem("user_id"), // 获取用户ID
    };
  },
  created() {
    this.fetchCollectionData(); // 初始化获取用户的收藏数据
  },
  methods: {
    goToNotationDetail(theoryknowledge) {
      // 调用后端接口更新浏览量
      this.incrementViewCount(theoryknowledge.theory_knowledge_id).then(() => {
        // 更新浏览量后，再进行页面跳转
        sessionStorage.setItem('theory_knowledge_id', theoryknowledge.theory_knowledge_id);
        this.$router.push({ path: '/knowledge/' + theoryknowledge.theory_knowledge_id });
      }).catch(error => {
        console.error('浏览量更新失败：', error);
        // 即使浏览量更新失败，也进行页面跳转
        sessionStorage.setItem('theory_knowledge_id', theoryknowledge.theory_knowledge_id);
        this.$router.push({ path: '/knowledge/' + theoryknowledge.theory_knowledge_id });
      });
    },
    incrementViewCount(theoryKnowledgeId) {
      return axios.post(`/v1/tk/${theoryKnowledgeId}`).then(response => {
        console.log('View count incremented');
        return response;
      }).catch(error => {
        console.error('Failed to increment view count:', error);
        throw error;
      });
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.updateFilteredList();
    },
    fetchCollectionData() {
      // 获取用户收藏的乐理知识数据
      axios
        .get(`/v1/tk/${this.userId}`) // 返回该用户的收藏列表
        .then((response) => {
          this.knowledgeList = response.data;
          this.filteredKnowledge = this.knowledgeList; // 默认显示全部数据
        })
        .catch((error) => {
          console.error('获取收藏乐理知识数据失败：', error);
        });
    },

    queryInfo() {
      // 搜索和筛选
      let filteredList = this.knowledgeList;

      // 如果选择了分类，先根据分类过滤
      if (this.selectedCategory !== '全部') {
        filteredList = filteredList.filter(item => item.type === this.selectedCategory);
      }

      // 根据搜索关键词过滤
      if (this.queryStr.trim().length > 0) {
        filteredList = filteredList.filter(item => {
          const title = item.name || '';
          const type = item.type || '';
          return title.includes(this.queryStr.trim()) || type.includes(this.queryStr.trim());
        });
      }

      // 更新显示的过滤后的数据
      this.filteredKnowledge = filteredList;
    },
  },
};
</script>

<style>
.knowledge-out {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  overflow: hidden;
}

.knowledge-item {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}

.knowledge-cover {
  width: 100%;
  height: 200px; /* 固定图片的高度，确保占据卡片的上方区域 */
  object-fit: cover; /* 确保图片填充区域，不变形 */
}

.knowledge-info {
  padding: 10px;
  flex-grow: 1; /* 让文本区域填充剩余空间 */
  text-align: center;
}

.knowledge-info h4 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-top: 10px;
}

.knowledge-info p {
  font-size: 14px;
  color: #777;
}

.search-bar {
  margin-bottom: 20px;
  text-align: center;
}
</style>
